<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\BaseController;
use App\Models\Comment;
use App\Models\Star;
use Illuminate\Http\Request;

class StarController extends BaseController
{

    public $model = Star::class;

    public function index(Request $request) {
        $search = ['start_at' => '', 'end_at' => '', 'user_id' => '', 'user.nickname' => ''];
        $input = $request->input();
        $is_virtual = $request->input('is_virtual', -1);
        $child_type = \request('child_type');

        $user_field = ['nickname', 'avatar_url', 'ip', 'is_virtual'];
        $list = Star::apply($search, $input)
            ->withCertain('user', $user_field)
            ->withCertain('article_user', $user_field)
            ->withCertain('article', ['title', 'file_path'])
            ->when($is_virtual != -1, function ($q) use($is_virtual) {
                $q->whereHas('user', function ($qr) use($is_virtual) {
                    $qr->where('is_virtual', $is_virtual);
                });
            })
            ->when($child_type, function ($q) use($child_type) {
                $q->where('child_type', $child_type);
            })
            ->orderBy("id", "desc");
        $list = $list->paginate(per_page());
        foreach ($list as &$item) {
            if ($item->type == Star::TYPE_COMMENT) {
                $comment = Comment::find($item->entity_id);
                $item->comment_message = $comment->message ?? '';
            }
        }

        return $this->paginate($list);
    }

}

